import io from 'socket.io-client';
import { createSocketIOHelper } from '../src/util/tools';
import qrTerm from 'qrcode-terminal';

require('module-alias/register');
import { net as netAPI } from '../src/protocolConst.json';
let url = `ws://localhost:14000`;
let socket = io(url);
let shp = createSocketIOHelper(socket);

socket.on('connect', () => {
	console.log('connected');
	start('wellbye');
	start('cxz');
	// start();
});
socket.on('disconnect', () => {
	console.log('disconnected');
	clear();
});
socket.on('action', action => {
	console.log('*action*', action);
	if (action.type == netAPI.onScan) {
		qrTerm.generate(action.payload.qrCode, { small: true });
		console.log('need scan to login for', action.payload.id);
	}
});

function clear() {}

async function start(id) {
	console.log('startx');
	let res = await shp.sendActionAndWait(netAPI.requestLogin, { id }, 10 * 1000);
	console.log(res);

	if (!res.err) {
		console.log('wait for login');
		let filterMyError = action => action.type == netAPI.onLogin && action.payload.id == id;
		res = await shp.waitAction(filterMyError, 0);
		console.log('on login', res);
	} else {
		console.log('already logined');
	}

	res = await shp.sendActionAndWait(netAPI.getRooms, { id }, 10 * 1000);
	let contacts = <Array<any>>res.payload;
	// console.log('get contacts', contacts);
	contacts = contacts.filter((v, k) => {
		// return v.name.indexOf('小冶') >= 0;
		return v.name.indexOf('测试') >= 0;
	});
	if (contacts.length == 1) {
		console.log('find target contact');
		await shp.sendActionAndWait(netAPI.sendMessage, {
			id,
			contactId: contacts[0].id,
			text: '欢欢喜喜过大年' + new Date().toLocaleTimeString(),
		});
	}

	let onerror = (async function() {
		let filterMyError = action => action.type == netAPI.onError && action.payload.id == id;
		let res = await shp.waitAction(filterMyError, 0);
		console.log('on error', res);
	})();
}
